package jdbc;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * JDBC工具类
 */
public class JDBCUtils {

    //定义相关属性
    private static String user;

    private static String password;

    private static String url;

    private static String driver;

    //在static代码块初始化
    static {
        Properties prop = new Properties();
        try {
            prop.load(new FileInputStream("src\\mysql3.properties"));
            //读取相关属性
            user = prop.getProperty("user");
            password = prop.getProperty("password");
            url = prop.getProperty("url");
            driver = prop.getProperty("driver");
        } catch (Exception e) {
            //将编译异常转换成运行异常
            //调用者可以选择捕获异常，也可以选择默认处理该异常
            throw new RuntimeException(e);
        }
    }


    //连接数据库
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //关闭相关资源
    /*
        1.ResultSet 结果集
        2.Statement 或者 PrepareStatement
        3.Connection
        如果需要关闭资源，就传入对象，否则传入 null
     */
    public static void close(ResultSet set, Statement stmt, Connection conn) {
        // 判断是否为空
        try {
            if (set != null) {
                set.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
